我們知道在Servlet中可以透過Filter過濾器來過濾請求或是對响應加工處理,而Filter是Servlet容器管理的元件我們不好從Spring MVC調用它,所以SpringMVC透過Interceptor攔截器來處理這類的需求。
(1) 請參考Day27 module
(2) Demo用Controller
@Controller
@ResponseBody
public class InterceptorController {
@GetMapping("InterceptorDemo")
public String interceptorDemo(){
System.out.println("InterceptorDemo method invoked");
return "Hello World";
}
}
在請求執行目標方法(Controller中的方法)前後進行攔截處理,使用場景:權限驗證、日誌紀錄、國際化i18n處理等等。
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!--設置排除路徑<mvc:exclude-mapping path=""/>-->
<bean class="com.swj.MyInterceptor1"></bean>
</mvc:interceptor>
</mvc:interceptors>
MyInterceptor1
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor1.preHandle ");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor1.postHandle ");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor1.afterCompletion ");
}
}
訪問InterceptorDemo
如果有多個攔截器運行,那麼它的執行順序就會是他配置的順序,我們在xml設定檔的interceptor1前面在設置一個interceptor2,建立Interceptor2.java
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!--設置排除路徑<mvc:exclude-mapping path=""/>-->
<bean class="com.swj.MyInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
最後以一個圖片總結執行順序